<script setup lang="ts">
import type { PropType } from 'vue';

import type { FileModel } from '#/api';

import { ref, watch } from 'vue';

import { useVModel } from '@vueuse/core';
import { Upload } from 'ant-design-vue';

import { asyncFindUrlById, uploadFile } from '#/api';
import { Icon } from '#/components/icon';

defineOptions({
  inheritAttrs: false,
});
const props = defineProps({
  // 文件id
  value: {
    type: String,
    default: '',
  },
  // 上传文件的参数
  uploadParams: {
    type: Object as PropType<FileModel.FileUploadVO>,
    default: () => ({}),
  },
});
const emits = defineEmits(['update:value']);
const previewUrl = ref<string>('');
// useVModel： 实现父子组件之间的 value 参数双向绑定
const mValue = useVModel(props, 'value', emits, {
  defaultValue: props.value,
  passive: true,
});
watch(
  () => mValue.value,
  () => {
    previewUrl.value = '';
    load(mValue.value);
  },
  { immediate: true },
);

function load(fileId: string) {
  if (!fileId) {
    return;
  }
  asyncFindUrlById(fileId).then((res) => {
    if (res.code === 0) {
      previewUrl.value = res.data as string;
    }
  });
}

const customRequest = (e: any) => {
  uploadFile({
    file: e.file,
    ...props.uploadParams,
  }).then((data: any) => {
    mValue.value = data.id;
  });
};
const handleRemove = (e: Event) => {
  e.stopPropagation();
  mValue.value = '';
};
</script>
<template>
  <Upload
    :custom-request="customRequest"
    :show-upload-list="false"
    list-type="picture-card"
  >
    <div v-if="mValue" class="m-avatar-wrap">
      <Icon
        class="m-avatar-icon-delete"
        icon="ant-design:delete-outlined"
        @click="handleRemove"
      />
      <img :src="previewUrl" width="100%" />
    </div>
    <Icon v-else icon="ant-design:plus-outlined" />
  </Upload>
</template>
<style lang="less" scoped>
.m-avatar-wrap {
  position: relative;
  height: 102px;
  .m-avatar-icon-delete {
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
  }
}
</style>
